package com.api.browser.service.impl;

import com.api.browser.bean.SearchConditionOption;
import com.api.browser.service.BrowserService;
import com.api.browser.util.BrowserConstant;
import com.api.browser.util.SqlUtils;
import com.engine.kq.biz.KQAttFlowSetComInfo;
import com.engine.kq.biz.KQSettingsBiz;
import com.engine.kq.enums.KQSettingsEnum;
import com.engine.kq.util.KQTransMethod;
import com.engine.kq.wfset.util.KQ122Util;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假类型
 *
 * @author 吕益
 *
 */
public class LeaveTypeBrowserService extends BrowserService {

    @Override
    public Map<String, Object> getBrowserData(Map<String, Object> params) throws Exception {

        Map<String, Object> apidatas = new HashMap<String, Object>();
        List<SearchConditionOption> options = new ArrayList<SearchConditionOption>();
        RecordSet rs = new RecordSet();
        KQ122Util kq122Util = new KQ122Util();
        boolean isKQOpen = kq122Util.is122Open();
        if(isKQOpen){
            String resourceId = user.getUID() + "";//暂时默认为当前登录人
            int beagenter = Util.getIntValue(Util.null2String(params.get("beagenter")), 0);
            if (beagenter > 0) {
                //如果存在代理人，显示代理人的请假类型
                resourceId = beagenter+ "";
            }
            //根据申请人带出请假类型
            String wfid = Util.null2String(params.get("wfid"));
            KQAttFlowSetComInfo kqAttFlowSetComInfo = new KQAttFlowSetComInfo();
            Map<String,Object> dependCfg = new HashMap<String,Object>();
            dependCfg = kqAttFlowSetComInfo.getDependCfgByWfId(wfid);

            boolean isFromWf = StringUtils.isNotBlank(wfid) ;

            if(dependCfg != null && isFromWf ){
                String resourceField = "";
                for(Map.Entry<String,Object> me : dependCfg.entrySet()){
                    List<String> resourceFields = (List<String>) me.getValue();
                    if(resourceFields != null && !resourceFields.isEmpty()){
                        //现在只是根据申请人id来获取
                        resourceField = Util.null2String(resourceFields.get(0));
                    }
                }
                if(resourceField.length() > 0){
                    resourceField = "field"+resourceField.substring(0,resourceField.indexOf("_"));
                    resourceId = Util.null2String(params.get(resourceField));
                }
            }

            String name = Util.null2String(params.get("name"));//假期规则名称
            String subcompanyId = "";
            String departmentId = "";
            try {
                if(resourceId == null || "".equals(resourceId)) {
                    resourceId=user.getUID() + "";
                }
                boolean show_leave_type_unit = KQSettingsBiz.showLeaveTypeSet(KQSettingsEnum.LEAVETYPE_UNIT.getMain_key());
                ResourceComInfo resourceComInfo = new ResourceComInfo();
                subcompanyId = resourceComInfo.getSubCompanyID(resourceId);
                departmentId = resourceComInfo.getDepartmentID(resourceId);

                /**
                 * 加载应用范围为总部的以及应用范围为分部(但是范围中包含了所属分部ID)的假期规则
                 */
                RecordSet recordSet = new RecordSet();
                String sql = "select * from kq_LeaveRules ";
                String sqlWhere = " where (isDelete is null or isDelete <>1) and isEnable=1 ";
                if (!name.equals("")) {
                    sqlWhere += " and leaveName like '%" + name + "%'";
                }
                /*如果找不到人员所在分部，则只返回应用范围为总部的假期规则*/
                if(isFromWf) {
                    if (!resourceId.equals("")) {
                        if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                            sqlWhere += " and ( (scopeType=3 and ','+scopeValue+',' like '%," + resourceId + ",%') ";
                        } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                            sqlWhere += " and ( (scopeType=3 and concat(',',scopeValue,',') like '%," + resourceId + ",%') ";
                        } else {
                            sqlWhere += " and ( (scopeType=3 and ','||scopeValue||',' like '%," + resourceId + ",%') ";
                        }
                    }
                    if (!departmentId.equals("")) {
                        if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                            sqlWhere += " or  (scopeType=2 and ','+scopeValue+',' like '%," + departmentId + ",%') ";
                        } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                            sqlWhere += " or  (scopeType=2 and concat(',',scopeValue,',') like '%," + departmentId + ",%') ";
                        } else {
                            sqlWhere += " or  (scopeType=2 and ','||scopeValue||',' like '%," + departmentId + ",%') ";
                        }
                    }
                    if (!subcompanyId.equals("")) {
                        if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                            sqlWhere += " or  (scopeType=1 and ','+scopeValue+',' like '%," + subcompanyId + ",%') ";
                        } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                            sqlWhere += " or  (scopeType=1 and concat(',',scopeValue,',') like '%," + subcompanyId + ",%') ";
                        } else {
                            sqlWhere += " or  (scopeType=1 and ','||scopeValue||',' like '%," + subcompanyId + ",%') ";
                        }
                    }

                    sqlWhere += " or scopeType=0 )";

                }
                sql = sql + sqlWhere + " order by showOrder,id ";

                recordSet.executeQuery(sql);
                /*如果指定人员所在分部下面单独设置过假期规则，则取分部下面的假期规则*/
                while (recordSet.next()) {
                    String leaveName = recordSet.getString("leaveName");//假期规则名称
                    String minimumUnit = recordSet.getString("minimumUnit");//最小请假单位
                    String computingMode = recordSet.getString("computingMode");//请假时长计算方式

                    KQTransMethod kqTransMethod = new KQTransMethod();

//                String showName = leaveName + "(" + kqTransMethod.getMinimumUnitName(minimumUnit, "" + user.getLanguage()) + "-" + kqTransMethod.getComputingModeName(computingMode, "" + user.getLanguage()) + ")";
                    String showName = leaveName;
                    if(show_leave_type_unit){
                        showName += "(" + kqTransMethod.getMinimumUnitName4Browser(minimumUnit, "" + user.getLanguage())+ ")";
                    }
                    options.add(new SearchConditionOption(recordSet.getString("id"), showName));
                }

                // 增加应用范围为其他的逻辑
                if (isFromWf && !resourceId.equals("")) {
                    String htztValue = null;
                    recordSet.execute("SELECT field17 FROM cus_fielddata WHERE scope = 'HrmCustomFieldByInfoType' and scopeid = 3 " +
                            "AND id = " + resourceId);
                    if (recordSet.next()) {
                        htztValue = recordSet.getString("field17");
                    }
                    if (StringUtils.isNotEmpty(htztValue)) {
                        String sqlT = "SELECT id FROM uf_jqhtztglb WHERE sfyx = 1 ";
                        if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                            sqlT += " and (','+CAST(htzt AS VARCHAR(MAX))+',' like '%," + htztValue + ",%') ";
                        } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                            sqlT += " and (concat(',',htzt,',') like '%," + htztValue + ",%') ";
                        } else {
                            sqlT += " and (','||htzt||',' like '%," + htztValue + ",%') ";
                        }

                        sql = "select * from kq_LeaveRules ";
                        sqlWhere = " where (isDelete is null or isDelete <>1) and isEnable=1 ";
                        if (!name.equals("")) {
                            sqlWhere += " and leaveName like '%" + name + "%'";
                        }
                        sqlWhere += " and scopeType in (" + sqlT + ") ";
                        sql = sql + sqlWhere + " order by showOrder,id ";
                        new BaseBean().writeLog("LeaveTypeBrowserService other sql:" + sql);

                        recordSet.executeQuery(sql);
                        /*如果指定人员所在分部下面单独设置过假期规则，则取分部下面的假期规则*/
                        while (recordSet.next()) {
                            String leaveName = recordSet.getString("leaveName");//假期规则名称
                            String minimumUnit = recordSet.getString("minimumUnit");//最小请假单位
                            String computingMode = recordSet.getString("computingMode");//请假时长计算方式
                            KQTransMethod kqTransMethod = new KQTransMethod();
                            String showName = leaveName;
                            if(show_leave_type_unit){
                                showName += "(" + kqTransMethod.getMinimumUnitName4Browser(minimumUnit, "" + user.getLanguage())+ ")";
                            }
                            options.add(new SearchConditionOption(recordSet.getString("id"), showName));
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            apidatas.put(BrowserConstant.BROWSER_RESULT_DATA, options);
            return apidatas;
        }else{
            String name = Util.null2String(params.get("name"));
            String sqlwhere = " and field002=1 ";
            if (!name.equals("")) {
                sqlwhere += " and name like '%";
                sqlwhere += Util.fromScreen2(name, 7);
                sqlwhere += "%'";
            }
            sqlwhere  = SqlUtils.replaceFirstAnd(sqlwhere);

            //设置好搜索条件
            String sql = "select field004 as id ,field001 as name from hrmleavetypecolor ";
            sql = sql+sqlwhere;
            sql = sql+" order by field006 ";
            rs.executeSql(sql);
            while(rs.next()){
                options.add(new SearchConditionOption(rs.getString("id"),rs.getString("name")));
            }
            apidatas.put(BrowserConstant.BROWSER_RESULT_DATA, options);
            return apidatas;
        }

    }

}
